import { useEffect, useState } from "react";
import { createConnection } from "./Chat";


export default function Demo4()
{
    const [roomId, SetRoomId] = useState('general');
    const [show, SetShow] = useState(false);

    return (
        <>
            <label>
                Choose the chat room:{' '}
                <select
                value={roomId}
                onChange={e => SetRoomId(e.target.value)}
                >
                <option value="general">general</option>
                <option value="travel">travel</option>
                <option value="music">music</option>
                </select>
            </label>
            <button onClick={() => SetShow(!show)}>
                {show ? 'Close chat' : 'Open chat'}
            </button>
            {show && <hr />}
            {show && <ChatRoom roomId={roomId} />}
        </>
    );
}

function ChatRoom({ roomId }) {
    const [serverUrl, SetServerUrl] = useState('https://localhost:1234');

    // 挂载
    useEffect(() => {
        const connection = createConnection(serverUrl, roomId);
        connection.connect();
        return () => {
            // 生命周期 => 卸载
            connection.disconnect();
        };
    }, [roomId, serverUrl]);

    return (
        <>
            <label>
                Server URL:{' '}
                <input
                    value={serverUrl}
                    onChange={e => SetServerUrl(e.target.value)}
                />
            </label>
            <h1>Welcome to the {roomId} room!</h1>
        </>
    );
}